/*
MIT License

Copyright (c) 2020 www.joolun.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ruoyi.web.controller.wechat;

import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.URLUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.wechat.domain.ImageManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.bean.WxMpMassNews;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.WxMpMassTagMessage;
import me.chanjar.weixin.mp.bean.WxMpMassVideo;
import me.chanjar.weixin.mp.bean.draft.WxMpAddDraft;
import me.chanjar.weixin.mp.bean.draft.WxMpDraftArticles;
import me.chanjar.weixin.mp.bean.draft.WxMpUpdateDraft;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信素材
 *
 * @author yan
 * @date 2021-11-05
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(tags = {"素材管理"})
@RequestMapping("/wechat/wxMaterial")
public class WxMaterialController extends BaseController {
    private final WxMpService wxMpService;

    /**
     * 上传非图文微信素材
     *
     * @param mulFile
     * @param mediaType
     * @return
     */
    @ApiOperation(value = "上传非图文微信素材")
    @PostMapping("/materialFileUpload")
    public AjaxResult materialFileUpload(@RequestParam("file") MultipartFile mulFile,
                                         @RequestParam("title") String title,
                                         @RequestParam("introduction") String introduction,
                                         @RequestParam("mediaType") String mediaType,
                                         @RequestParam("appid") String appId) {
        wxMpService.switchover(appId);
        try {
            WxMpMaterial material = new WxMpMaterial();
            material.setName(mulFile.getOriginalFilename());
            if (WxConsts.MediaFileType.VIDEO.equals(mediaType)) {
                material.setVideoTitle(title);
                material.setVideoIntroduction(introduction);
            }
            File file = FileUtils.multipartFileToFile(mulFile);
            material.setFile(file);
            WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
            WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpMaterialService.materialFileUpload(mediaType, material);
            WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem();
            wxMpMaterialFileBatchGetResult.setName(file.getName());
            wxMpMaterialFileBatchGetResult.setMediaId(wxMpMaterialUploadResult.getMediaId());
            wxMpMaterialFileBatchGetResult.setUrl(wxMpMaterialUploadResult.getUrl());
            return AjaxResult.success(wxMpMaterialFileBatchGetResult);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("上传非图文微信素材失败" + e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传失败", e);
            return AjaxResult.error(e.getLocalizedMessage());
        }
    }

    /**
     * 上传图文消息内的图片获取URL
     *
     * @param mulFile
     * @return
     */
    @ApiOperation(value = "上传图文消息内的图片获取URL")
    @PostMapping("/newsImgUpload")
    public String newsImgUpload(@RequestParam("file") MultipartFile mulFile, @RequestParam("appid") String appId) throws Exception {
        wxMpService.switchover(appId);
        File file = FileUtils.multipartFileToFile(mulFile);
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        WxMediaImgUploadResult wxMediaImgUploadResult = wxMpMaterialService.mediaImgUpload(file);
        Map<Object, Object> responseData = new HashMap<>();
        responseData.put("link", wxMediaImgUploadResult.getUrl());
        return JSONUtil.toJsonStr(responseData);
    }


    /**
     * 通过id删除微信素材
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过id删除微信素材")
    @DeleteMapping
    public AjaxResult materialDel(@RequestParam("id") String id,
                                  @RequestParam("appid") String appId) {
        wxMpService.switchover(appId);
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        try {
            return AjaxResult.success(wxMpMaterialService.materialDelete(id));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("删除微信素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 分页查询2
     *
     * @param type
     * @return
     */
    @ApiOperation(value = "分页查询2微信素材")
    @GetMapping("/page-manager")
    public String getWxMaterialPageManager(Integer count, Integer offset, String type, String appid) throws WxErrorException {
        wxMpService.switchover(appid);
        List<ImageManager> listImageManager = new ArrayList<>();
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        List<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> list = wxMpMaterialService.materialFileBatchGet(type, offset, count).getItems();
        list.forEach(wxMaterialFileBatchGetNewsItem -> {
            ImageManager imageManager = new ImageManager();
            imageManager.setName(wxMaterialFileBatchGetNewsItem.getMediaId());
            imageManager.setUrl(wxMaterialFileBatchGetNewsItem.getUrl());
            imageManager.setThumb(wxMaterialFileBatchGetNewsItem.getUrl());
            listImageManager.add(imageManager);
        });
        return JSONUtil.toJsonStr(listImageManager);
    }

    /**
     * 获取微信视频素材
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "获取微信视频素材")
    @GetMapping("/materialVideo")
    public AjaxResult getMaterialVideo(String mediaId, String appid) {
        wxMpService.switchover(appid);
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        try {
            return AjaxResult.success(wxMpMaterialService.materialVideoInfo(mediaId));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取微信视频素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取微信图文素材-草稿箱
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "获取微信图文素材")
    @GetMapping("/image")
    public AjaxResult getImage(String mediaId, String appid) {
        wxMpService.switchover(appid);
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        try {
            return AjaxResult.success(wxMpMaterialService.materialNewsInfo(mediaId));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取微信图文素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取微信图文素材
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "获取微信图片素材")
    @GetMapping("/materialByImage")
    public AjaxResult getMaterialByImage(String mediaId, String appid) {
        logger.info("图片素材参数：{}", mediaId);
        try {
            Integer count = 1;
            Integer offset = 20;
            ImageManager listImageManager = getImageManagers(count, offset, mediaId, appid);
            logger.info("图片素材：{}", listImageManager);
            return AjaxResult.success(listImageManager);
        } catch (WxErrorException e) {
            return AjaxResult.error();
        }
    }

    private ImageManager getImageManagers(Integer count, Integer offset, String mediaId, String appid) throws WxErrorException {
        logger.info("进入图片素材循环,{}", count);
        wxMpService.switchover(appid);
        ImageManager imageManager = new ImageManager();
        WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
        WxMpMaterialFileBatchGetResult batchGetResult = wxMpMaterialService.materialFileBatchGet("image", count, offset);
        logger.info("图篇素材结果集：{}", batchGetResult);
        List<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> list = batchGetResult.getItems();
        logger.info("图篇素材结果集详情：{}", list);
        list.forEach(wxMaterialFileBatchGetNewsItem -> {
            logger.info("图篇素材ID：{}", wxMaterialFileBatchGetNewsItem.getMediaId());
            if (mediaId.equals(wxMaterialFileBatchGetNewsItem.getMediaId())) {
                imageManager.setName(wxMaterialFileBatchGetNewsItem.getMediaId());
                imageManager.setUrl(wxMaterialFileBatchGetNewsItem.getUrl());
                imageManager.setThumb(wxMaterialFileBatchGetNewsItem.getUrl());
                return;
            }
        });
        if (imageManager != null) {
            return imageManager;
        } else {
            if (batchGetResult.getItemCount() > offset) {
                count++;
                getImageManagers(count, offset, mediaId, appid);
            }
        }
        return imageManager;
    }


    /**
     * 获取微信素材直接文件
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "获取微信素材直接文件")
    @GetMapping("/materialOther")
    public ResponseEntity<byte[]> getMaterialOther(String mediaId, String fileName, String appid) throws Exception {
        wxMpService.switchover(appid);
        try {
            WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
            //获取文件
            InputStream is = wxMpMaterialService.materialImageOrVoiceDownload(mediaId);
            byte[] body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            //设置文件类型
            headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            headers.add("Content-Type", "application/octet-stream");
            HttpStatus statusCode = HttpStatus.OK;
            //返回数据
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            logger.info("素材返回值：{}", entity);
            return entity;
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取微信素材直接文件失败", e);
            return null;
        }
    }

    /**
     * 分页查询 -草稿箱
     *
     * @param page  分页对象
     * @param appid appid
     * @return
     */
    @ApiOperation(value = "分页查询微信素材")
    @GetMapping("/image/page")
    public AjaxResult page(Page page, String appid, String type) {
        try {
            wxMpService.switchover(appid);
            WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
            int count = (int) page.getSize();
            int offset = (int) page.getCurrent() * count - count;
            if (StringUtils.isNotEmpty(type)) {
                return AjaxResult.success(wxMpMaterialService.materialFileBatchGet(type, offset, count));
            } else {
                return AjaxResult.success(wxMpMaterialService.materialNewsBatchGet(offset, count));
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("查询素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取微信临时素材直接文件
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "获取微信临时素材直接文件")
    @GetMapping("/tempMaterialOther")
    public ResponseEntity<byte[]> getTempMaterialOther(String mediaId, String fileName, String appid) throws Exception {
        try {
            wxMpService.switchover(appid);
            WxMpMaterialService wxMpMaterialService = wxMpService.getMaterialService();
            //获取文件
            InputStream is = new FileInputStream(wxMpMaterialService.mediaDownload(mediaId));
            byte[] body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            //设置文件类型
            headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            headers.add("Content-Type", "application/octet-stream");
            HttpStatus statusCode = HttpStatus.OK;
            //返回数据
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            return entity;
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取微信素材直接文件失败", e);
            return null;
        }
    }


    /**
     * 分页查询 -草稿箱
     *
     * @param page  分页对象
     * @param appid appid
     * @return
     */
    @ApiOperation(value = "分页查询微信素材")
    @GetMapping("/page")
    public AjaxResult getWxMaterialPage(Page page, String appid) {
        try {
            wxMpService.switchover(appid);
            WxMpDraftService draftService = wxMpService.getDraftService();
            int count = (int) page.getSize();
            int offset = (int) page.getCurrent() * count - count;
            return AjaxResult.success(draftService.listDraft(offset, count));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("查询素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通过id删除微信图文素材--草稿箱
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过id删除微信图文素材")
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestParam("id") String id,
                             @RequestParam("appid") String appId) {
        wxMpService.switchover(appId);
        WxMpDraftService draftService = wxMpService.getDraftService();
        try {
            return AjaxResult.success(draftService.delDraft(id));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("删除微信素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 新增草稿后，开发者可以根据草稿指定的字段来下载草稿--草稿箱
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "新增草稿后，开发者可以根据草稿指定的字段来下载草稿")
    @GetMapping("/getInfo")
    public AjaxResult getInfo(@RequestParam("id") String id,
                              @RequestParam("appid") String appId) {
        wxMpService.switchover(appId);
        WxMpDraftService draftService = wxMpService.getDraftService();
        try {
            return AjaxResult.success(draftService.getDraft(id));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("删除微信素材失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 新增图文消息-草稿箱
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "新增图文消息")
    @PostMapping("/materialNews")
    public AjaxResult materialNewsUpload(@RequestBody JSONObject data) {
        try {
            String appid = data.getStr("appid");
            wxMpService.switchover(appid);
            JSONArray jSONArray = data.getJSONArray("articles");
            String release = data.getStr("release");
            List<WxMpDraftArticles> articles = jSONArray.toList(WxMpDraftArticles.class);
            articles.forEach(article -> {
                try {
                    processContent(wxMpService, article.getContent(), appid);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                    log.error("图文资源上传失败" + e.getMessage());
                }
            });
            WxMpAddDraft news = new WxMpAddDraft();
            news.setArticles(articles);
            WxMpDraftService wxMpDraftService = wxMpService.getDraftService();
            String s = wxMpDraftService.addDraft(news);
            log.info("返回的参数值:{}", s);
            if ("1".equals(release)) {
                wxMpService.switchover(appid);
                WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
                //发布
                String submit = getFreePublishService.submit(s);
                log.info("返回的文章ID :{}", submit);
                //模板消息
                String msgTemplate = data.getStr("msgTemplate");
                log.info("返回的参数值:{}", release);
                return AjaxResult.success("发布成功", submit);
            } else if ("2".equals(release)) {
                wxMpService.switchover(appid);
                WxMpMassTagMessage wxMpMassTagMessage = new WxMpMassTagMessage();
                wxMpMassTagMessage.setMediaId(s);
                wxMpMassTagMessage.setSendAll(true);
                wxMpMassTagMessage.setMsgType("mpnews");
                WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
                WxMpMassSendResult wxMpMassSendResult = wxMpMassMessageService.massGroupMessageSend(wxMpMassTagMessage);
                return AjaxResult.success(wxMpMassSendResult);
            }
            return AjaxResult.success("图文消息", s);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("新增图文失败" + e.getMessage());
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增图文失败", e);
            return AjaxResult.error(e.getLocalizedMessage());
        }
    }

    /**
     * 修改图文消息-草稿箱
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "修改图文消息")
    @PutMapping("/materialNews")
    public AjaxResult materialNewsUpdate(@RequestBody JSONObject data) {
        try {
            String appid = data.getStr("appid");
            wxMpService.switchover(appid);
            String mediaId = data.getStr("mediaId");
            String release = data.getStr("release");
            JSONArray jSONArray = data.getJSONArray("articles");
            List<WxMpDraftArticles> articles = jSONArray.toList(WxMpDraftArticles.class);
            WxMpDraftService wxMpDraftService = wxMpService.getDraftService();
            WxMpUpdateDraft wxMpUpdateDraft = new WxMpUpdateDraft();
            wxMpUpdateDraft.setMediaId(mediaId);
            int index = 0;
            for (WxMpDraftArticles article : articles) {
                wxMpUpdateDraft.setIndex(index);
                wxMpUpdateDraft.setArticles(article);
                wxMpDraftService.updateDraft(wxMpUpdateDraft);
                index++;
            }
            if ("1".equals(release)) {
                wxMpService.switchover(data.getStr("appid"));
                WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
                //发布
                String submit = getFreePublishService.submit(mediaId);
                log.info("返回的文章ID :{}", submit);
                //模板消息
                String msgTemplate = data.getStr("msgTemplate");
                log.info("返回的参数值:{}", release);
                return AjaxResult.success("发布成功", submit);
            } else if ("2".equals(release)) {
                wxMpService.switchover(data.getStr("appid"));
                WxMpMassTagMessage wxMpMassTagMessage = new WxMpMassTagMessage();
                wxMpMassTagMessage.setMediaId(mediaId);
                wxMpMassTagMessage.setSendAll(true);
                wxMpMassTagMessage.setMsgType("mpnews");
                WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
                return AjaxResult.success(wxMpMassMessageService.massGroupMessageSend(wxMpMassTagMessage));
            }
            return AjaxResult.success();
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("修改图文失败" + e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改图文失败", e);
            return AjaxResult.error(e.getLocalizedMessage());
        }
    }

    /**
     * 发布能力
     */
    @GetMapping("/freePublic/submit")
    public AjaxResult submit(String appid, String id) {
        wxMpService.switchover(appid);
        WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
        try {
            String submit = getFreePublishService.submit(id);
            return AjaxResult.success("发布成功", submit);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("发布失败:{}", e);
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 删除发布文章
     */
    @DeleteMapping("/freePublic/remove")
    public AjaxResult remove(String appid, String id, Integer index) {
        wxMpService.switchover(appid);
        WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
        Boolean push;
        try {
            if (index != null) {
                push = getFreePublishService.deletePush(id, index);
            } else {
                push = getFreePublishService.deletePushAllArticle(id);
            }
            if (push) {
                return AjaxResult.success("删除成功", push);
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("删除发布文章:{}", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取成功发布列表
     *
     * @param page  分页对象
     * @param appid appid
     * @return
     */
    @ApiOperation(value = "获取成功发布列表")
    @GetMapping("/freePublic/batchget")
    public AjaxResult batchget(Page page, String appid) {
        try {
            wxMpService.switchover(appid);
            WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
            int count = (int) page.getSize();
            int offset = (int) page.getCurrent() * count - count;
            return AjaxResult.success(getFreePublishService.getPublicationRecords(offset, count));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通过 article_id 获取已发布的图文信息。
     *
     * @param id    文章ID
     * @param appid appid
     * @return
     */
    @ApiOperation(value = "获取成功发布列表")
    @GetMapping("/freePublic/getArticle")
    public AjaxResult getArticle(String id, String appid) {
        try {
            wxMpService.switchover(appid);
            WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
            return AjaxResult.success(getFreePublishService.getArticleFromId(id));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通过 article_id 获取已发布的图文信息。
     *
     * @param id    分页对象
     * @param appid article_id
     * @return
     */
    @ApiOperation(value = "获取成功发布列表")
    @GetMapping("/freePublic/getPushStatus")
    public AjaxResult getPushStatus(String id, String appid) {
        try {
            wxMpService.switchover(appid);
            WxMpFreePublishService getFreePublishService = wxMpService.getFreePublishService();
            return AjaxResult.success(getFreePublishService.getPushStatus(id));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传群发用的图文消息，上传后才能群发图文消息.
     */
    @ApiOperation(value = "上传群发用的图文消息")
    @PostMapping("/freePublic/massNews")
    public AjaxResult massNews(@RequestBody JSONObject data) {
        try {
            wxMpService.switchover(data.getStr("appid"));
            String mpMassNews = data.getStr("wxMpMassNews");
            WxMpMassNews wxMpMassNews = JSONUtil.toBean(mpMassNews, WxMpMassNews.class);
            WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
            return AjaxResult.success(wxMpMassMessageService.massNewsUpload(wxMpMassNews));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传群发用的视频，上传后才能群发视频消息.
     */
    @ApiOperation(value = "上传群发用的视频")
    @PostMapping("/freePublic/massVideoUpload")
    public AjaxResult massVideoUpload(@RequestBody JSONObject data) {
        try {
            wxMpService.switchover(data.getStr("appid"));
            String massVideoUpload = data.getStr("massVideoUpload");
            WxMpMassVideo wxMpMassVideo = JSONUtil.toBean(massVideoUpload, WxMpMassVideo.class);
            WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
            return AjaxResult.success(wxMpMassMessageService.massVideoUpload(wxMpMassVideo));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 分组群发消息.
     * 如果发送图文消息，必须先使用 massNewsUpload(WxMpMassNews) 获得media_id，然后再发送
     * 如果发送视频消息，必须先使用 massVideoUpload(WxMpMassVideo) 获得media_id，然后再发送
     */
    @ApiOperation(value = "分组群发消息")
    @PostMapping("/freePublic/massGroupMessageSend")
    public AjaxResult massGroupMessageSend(@RequestBody JSONObject data) {
        try {
            wxMpService.switchover(data.getStr("appid"));
            String massTagMessage = data.getStr("massTagMessage");
            WxMpMassTagMessage wxMpMassTagMessage = JSONUtil.toBean(massTagMessage, WxMpMassTagMessage.class);
            WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
            return AjaxResult.success(wxMpMassMessageService.massGroupMessageSend(wxMpMassTagMessage));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 按openId列表群发消息.
     * 如果发送图文消息，必须先使用 massNewsUpload(WxMpMassNews) 获得media_id，然后再发送
     * 如果发送视频消息，必须先使用 massVideoUpload(WxMpMassVideo) 获得media_id，然后再发送
     * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN
     */
    @ApiOperation(value = "按openId列表群发消息")
    @PostMapping("/freePublic/massOpenIdsMessageSend")
    public AjaxResult massOpenIdsMessageSend(@RequestBody JSONObject data) {
        try {
            wxMpService.switchover(data.getStr("appid"));
            String massOpenIdsMessageSend = data.getStr("massOpenIdsMessageSend");
            WxMpMassOpenIdsMessage wxMpMassOpenIdsMessage = JSONUtil.toBean(massOpenIdsMessageSend, WxMpMassOpenIdsMessage.class);
            WxMpMassMessageService wxMpMassMessageService = wxMpService.getMassMessageService();
            return AjaxResult.success(wxMpMassMessageService.massOpenIdsMessageSend(wxMpMassOpenIdsMessage));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("获取成功发布列表", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 处理内容
     *
     * @param wxMpService WxMpService
     * @param content     内容
     * @return String
     * @throws WxErrorException
     */
    private String processContent(WxMpService wxMpService, String content, String appid) throws WxErrorException {
        if (org.apache.commons.lang3.StringUtils.isBlank(content)) {
            return content;
        }
        String imgReg = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        List<String> imgList = ReUtil.findAllGroup1(imgReg, content);
        logger.info("图片输出：{}",imgList);
        for (int j = 0; j < imgList.size(); j++) {
            String imgSrc = imgList.get(j);
            String filepath = URLUtils.getParam(imgSrc, "filepath");

            if (org.apache.commons.lang3.StringUtils.isBlank(filepath)) {
                //网络图片URL，需下载到本地
                String filename = System.currentTimeMillis() + ".png";
                String downloadPath = RuoYiConfig.getDownloadPath() + filename;
                logger.info("图片路径：{}",downloadPath);
                long size = HttpUtil.downloadFile(imgSrc, cn.hutool.core.io.FileUtil.file(downloadPath));
                filepath = downloadPath;
            }
            wxMpService.switchover(appid);
            WxMediaImgUploadResult wxMediaImgUploadResult = wxMpService.getMaterialService().mediaImgUpload(new File(filepath));
            content = org.apache.commons.lang3.StringUtils.replace(content, imgList.get(j), wxMediaImgUploadResult.getUrl());
        }
        return content;
    }
}
